//
//  HomeData.swift
//  Core
//
//  Created by raymond Peng on 2018/11/9.
//  Copyright © 2018 raymond Peng. All rights reserved.
//

import Foundation
import Domain
import DAL

public class ShoppingData {
    public static let `default`: IShoppingData = {
        let communicator = ServerCommunicator.instanceOf(type: .urlsession)
        return ShoppingDataImp(communicator: communicator)
    }()

    private init() { }
}

class ShoppingDataImp: IShoppingData {

    private let _communicator: IServerCommunicator

    private var _shoppingData: GoodsListEntity?

    init(communicator: IServerCommunicator) {
        _communicator = communicator
    }

    func fetchShoppingData(completion: @escaping (IShoppingDataListEntity?, CommonError?) -> Void) {
        let req = DataRequestMaker.shoppingData.getDataRequest()
        _communicator.requestWith(request: req, completionHandler: { [weak self] in
            switch $0 {
            case .success(let respData):
                let result: TopLevelDataResult<GoodsListEntity> = deserializeTopLevelObjWith(data: respData)
                self?._shoppingData = result.0?.data
                completion(result.0?.data, result.1)
            case .failed(_, let err):
                completion(nil, err)
            }
        })
    }

    func getCategoryList() -> [ICategoryEntity] {
        return _shoppingData?.categories ?? []
    }

    func getProductArrayBy(categoryID: String) -> [IProductEntity] {
        let arr = _shoppingData?.products?.filter({ $0.category?.categoryID == categoryID })
        return arr ?? []
    }

    func getProductBy(productID: String) -> IProductEntity? {
        return _shoppingData?.products?.first(where: { $0.ids == productID })
    }

    func getSKUArrayBy(productID: String) -> [ISKUEntity] {
        return _shoppingData?.products?.first(where: { $0.ids == productID })?.skus ?? []
    }
}
